package a2dp.vol.chat;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPException;

import a2dp.vol.chat.MyApplication;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class ConnectActivity extends Activity {

	ProgressDialog pd;
	String address, user, pwd;
	int port;
	String serviceName;
	boolean sasl;
	int tls;
	boolean reconnect;
	EditText txfaddress, txtPort, txfserviceName, txfUser, txfPass;
	CheckBox boxSasl, boxReconnect;
	RadioButton radioTlsEnabled, radioTlsDisabled, radioTlsRequired;
	ConnectionConfiguration config;
	ServiceItem si;
	ServiceDB sdb;
	private MyApplication application;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.connect);
		this.application = (MyApplication) this.getApplication();

		Button btnConnect = (Button) findViewById(R.id.btnConnect);
		txfaddress = (EditText) findViewById(R.id.editAddress);
		txtPort = (EditText) findViewById(R.id.editPort);
		txfserviceName = (EditText) findViewById(R.id.editService);
		boxSasl = (CheckBox) findViewById(R.id.checkBoxSASL);
		radioTlsEnabled = (RadioButton) findViewById(R.id.radioEnabled);
		radioTlsDisabled = (RadioButton) findViewById(R.id.radioDisabled);
		radioTlsRequired = (RadioButton) findViewById(R.id.radioRequired);
		boxReconnect = (CheckBox) findViewById(R.id.checkBoxReconnect);
		//txfUser = (EditText) findViewById(R.id.txfUser);
		//txfPass = (EditText) findViewById(R.id.txfPassword);
		
		si = new ServiceItem();
		this.sdb = new ServiceDB(application);
		user = " ";
		pwd = " ";

		Intent i = this.getIntent();
		int key = i.getIntExtra("key", -1);
		if (key >= 0) {
			si = sdb.getSI(key);
			address = si.getAddress();
			txfaddress.setText(address);
			port = si.getPort();
			txtPort.setText(Integer.toString(port));
			serviceName = si.getSname();
			txfserviceName.setText(serviceName);
			sasl = si.bgetSasl();
			boxSasl.setChecked(sasl);
			
			switch(si.getTls()){
			
			case -1:
				radioTlsDisabled.setChecked(true);
				tls = -1;
				break;
			case 0:
				radioTlsEnabled.setChecked(true);
				tls = 0;
				break;
			case 1:
				radioTlsRequired.setChecked(true);
				tls = 1;
				break;
			default:
				radioTlsEnabled.setChecked(true);
				break;		
			}
			reconnect = si.bgetReconnect();
			boxReconnect.setChecked(reconnect);
			user = si.getUser();
			//txfUser.setText(user);
			pwd = si.getPwd();
			//txfPass.setText(pwd);
		}

		
		btnConnect.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				address = txfaddress.getText().toString();

				try {
					port = Integer.parseInt(txtPort.getText().toString());
				} catch (NumberFormatException e) {
					e.printStackTrace();
					return;
				}
				serviceName = txfserviceName.getText().toString();
				config = new ConnectionConfiguration(address, port, serviceName);
				sasl = boxSasl.isChecked();
				config.setSASLAuthenticationEnabled(sasl);
				if (radioTlsRequired.isChecked()) {
					tls = 1;
					config.setSecurityMode(ConnectionConfiguration.SecurityMode.required);
				} else if (radioTlsDisabled.isChecked()) {
					tls = -1;
					config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
				} else {
					tls = 0;
					config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
				}
				reconnect = boxReconnect.isChecked();
				config.setReconnectionAllowed(reconnect);
				new DoConnect().execute();

			}
		});
	}

	class DoConnect extends AsyncTask<String, Boolean, Boolean> {

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			pd.dismiss();
			if (result) {
				Toast.makeText(a2dp.vol.chat.ConnectActivity.this, "Connected",
						Toast.LENGTH_LONG).show();
				/*
				 * Intent i = new Intent();
				 * i.setClass(a2dp.vol.chat.ConnectActivity.this,
				 * LoginActivity.class); i.putExtra("address", address);
				 * //i.putExtra("config", config); startActivity(i); finish();
				 */
				if (sdb.getSI(address) == null) {
					si.setAddress(address);
					si.setPort(port);
					si.setReconnect(reconnect);
					si.setSasl(sasl);
					si.setTls(tls);
					si.setSname(serviceName);
					si.setUser(user);
					si.setPwd(pwd);
					sdb.insert(si);
				} else {
					si.setAddress(address);
					si.setPort(port);
					si.setReconnect(reconnect);
					si.setSasl(sasl);
					si.setTls(tls);
					si.setSname(serviceName);
					si.setUser(user);
					si.setPwd(pwd);
					sdb.update(si);
					if(user.length() >3 && pwd.length() > 3)new DoLogin().execute(user, pwd);
				}

				setContentView(R.layout.login);

				Button btnLogin = (Button) findViewById(R.id.btnLogin);
				txfUser = (EditText)findViewById(R.id.txfUser);
				txfPass = (EditText)findViewById(R.id.txfPassword);
				if(user.length() > 1)txfUser.setText(user);
				if(pwd.length() > 1)txfPass.setText(pwd);
				// new DoConnect().execute();
				btnLogin.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View arg0) {

						String user1 = txfUser.getText().toString();
						user = user1;
						String pass1 = txfPass.getText().toString();
						pwd = pass1;
						new DoLogin().execute(user, pwd);
					}
				});
			} else {
				AlertDialog.Builder adBuilder = new AlertDialog.Builder(
						ConnectActivity.this);
				adBuilder
						.setMessage(
								"Connection unsuccessful.\nPlease try again.")
						.setCancelable(false)
						.setPositiveButton("OK",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();
									}
								});
				AlertDialog alert = adBuilder.create();
				alert.show();
			}
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pd = ProgressDialog.show(ConnectActivity.this, "Please Wait",
					"Connecting...");
		}

		@Override
		protected Boolean doInBackground(String... params) {
			boolean result = false;

			try {
				ConnectionHelper.connect(config);
				result = Boolean.TRUE;
			} catch (XMPPException e) {
				result = Boolean.FALSE;
				e.printStackTrace();
			}
			return result;
		}

	}

	class DoLogin extends AsyncTask<String, Boolean, Boolean> {

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			pd.dismiss();
			if (result) {
				startService(new Intent(ConnectActivity.this,
						NChatService.class));
				Intent cla = new Intent();
				cla.setClass(a2dp.vol.chat.ConnectActivity.this,
						ContactListActivity.class);
				cla.putExtra("address", address);
				if (sdb.getSI(address) == null) {
					si.setAddress(address);
					si.setPort(port);
					si.setReconnect(reconnect);
					si.setSasl(sasl);
					si.setTls(tls);
					si.setSname(serviceName);
					si.setUser(user);
					si.setPwd(pwd);
					sdb.insert(si);
				} else {
					si.setAddress(address);
					si.setPort(port);
					si.setReconnect(reconnect);
					si.setSasl(sasl);
					si.setTls(tls);
					si.setSname(serviceName);
					si.setUser(user);
					si.setPwd(pwd);
					sdb.update(si);
				}
				startActivity(cla);
				// startActivity(new Intent(ConnectActivity.this,
				// ContactListActivity.class));
				ConnectActivity.this.finish();
			} else {
				AlertDialog.Builder adBuilder = new AlertDialog.Builder(
						ConnectActivity.this);
				adBuilder
						.setMessage("Login unsuccessful.\nPlease try again.")
						.setCancelable(false)
						.setPositiveButton("OK",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();
									}
								});
				AlertDialog alert = adBuilder.create();
				alert.show();
			}
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pd = ProgressDialog.show(ConnectActivity.this, "Please Wait",
					"Logging in...");
		}

		@Override
		protected Boolean doInBackground(String... params) {
			boolean result = false;
			String user = params[0];
			String pass = params[1];
			try {
				ConnectionHelper.connect(config);
				ConnectionHelper.getConnection();
				ConnectionHelper.login(user, pass);
				//ConnectionHelper.conn.
				result = Boolean.TRUE;
			} catch (XMPPException e) {
				result = Boolean.FALSE;
				e.printStackTrace();
			}
			return result;
		}

	}
}